// createModal.js
import Vue from 'vue'
import Modal from './Modal.vue'

/**
 * 创建命令式弹窗
 * @param {Component} component - 要展示的Vue组件
 * @param {Object} options - 配置选项
 * @param {Object} options.props - 传递给组件的props
 * @param {Object} options.on - 组件事件监听器
 * @param {Object} options.config - 弹窗配置
 * @returns {Promise} 返回Promise，确认时resolve，取消时reject
 */
export function createModal(component, { props = {}, on = {}, config = {} }) {
  // 创建Modal构造器
  const ModalConstructor = Vue.extend(Modal)

  // 创建Modal实例
  const instance = new ModalConstructor({
    propsData: {
      contentComponent: component,
      componentProps: props,
      componentEvents: on,
      title: config.header || '提示',
      closeOnClickOverlay: config.closeOnClickOverlay || false,
      customButton: config.customButton || false
    }
  })

  // 手动挂载实例
  instance.$mount()
  document.body.appendChild(instance.$el)

  // 处理确认回调
  const originalSuccess = config.success || (() => {})
  config.success = function(data) {
    originalSuccess(data)
    instance.close()
  }

  // 返回Promise
  return instance.show().then(data => {
    typeof config.success === 'function' && config.success(data)
    return data
  }).catch(error => {
    typeof config.fail === 'function' && config.fail(error)
    throw error
  })
}
